package com.ettractions.kiosk.assets
{
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.net.URLRequest;
	import flash.utils.Dictionary;

	public class AssetsLoader extends EventDispatcher
	{
		public var assets:AssetsStore;
		
		private var _request:AssetsLoadRequest;		
		
		private var _loaderPathMap:Dictionary;
		
		private var _assetLoadedCount:uint;
		
		public function AssetsLoader(request:AssetsLoadRequest = null)
		{
			if (request)
				loadAssets(request);
		}
		
		public function loadAssets(request:AssetsLoadRequest):void
		{
			assets = new AssetsStore();
			
			_request = request;
			
			_loaderPathMap = new Dictionary(true);
			
			_assetLoadedCount = 0;
			
			for each (var path:String in _request.paths)
			{
				var loader:Loader = new Loader();
				
				loader.contentLoaderInfo.addEventListener(Event.COMPLETE, handleAssetLoadComplete);
				loader.load(new URLRequest(path));
				
				_loaderPathMap[loader] = path;
			}
		}
		
		private function handleAssetLoadComplete(event:Event):void
		{
			var loaderInfo:LoaderInfo = LoaderInfo(event.target);
			var loader:Loader = loaderInfo.loader;
			var path:String = _loaderPathMap[loader];
			
			loaderInfo.removeEventListener(Event.COMPLETE, handleAssetLoadComplete);
			
			assets.put(path, loader.content);
			
			delete _loaderPathMap[loader];
			
			if (++_assetLoadedCount == _request.paths.length)
				dispatchEvent(new Event(Event.COMPLETE));
		}
	}
}